import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumnType} from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import {Button, message, Form, Popconfirm, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import {addIntl, getIntlPage, batchDelIntl, updateIntl} from './service';
import randomString from "@/utils/randomString";

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);

  const [editForm] = Form.useForm()
  const [addForm] = Form.useForm()

  const columns: ProColumnType<any>[] = [
    {
      title: '序号',
      dataIndex: '#',
      key: '#',
      width: 80,
      hideInSearch: true,
      hideInForm: true,
      fixed: 'left',
      render(dom, entity, index) {
        return index + 1;
      },
      editable: false,
    },
    {
      title: '国际化Key',
      dataIndex: 'intlKey',
      fieldProps: {
        placeholder: '请输入国际化Key'
      },
      formItemProps: {
        rules: [{required: true, message: '此项为必填项'}],
      }
    },
    {
      title: '中文',
      dataIndex: 'chinese',
      valueType: 'textarea',
      fieldProps: {
        placeholder: '请输入中文'
      },
      ellipsis: true,
      formItemProps: () => {
        return {
          rules: [{required: true, message: '此项为必填项'}],
        };
      },
      render(dom) {
        return <div style={{width: 300}}>{dom}</div>
      }
    },
    {
      title: '英文',
      dataIndex: 'english',
      valueType: 'textarea',
      ellipsis: true,
      fieldProps: {
        placeholder: '请输入英文'
      },
      formItemProps: () => {
        return {
          rules: [{required: true, message: '此项为必填项'}],
        };
      },
      render(dom) {
        return <div style={{width: 300}}>{dom}</div>
      }
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 100,
      valueType: 'option',
      render: (_, record: any, ) => {
        return [
          <BetaSchemaForm<any>
            key="edit"
            form={editForm}
            trigger={<a
              onClick={() => {
                editForm.resetFields()
                editForm.setFieldsValue({
                  ...record,
                })
              }}
            >
              编辑
            </a>}
            layoutType={'ModalForm'}
            modalProps={{
              width: 500,
              title: '编辑国际化'
            }}
            // rowProps={{
            //   gutter: [16, 16],
            // }}
            // colProps={{
            //   span: 12,
            // }}
            // grid={false}
            onFinish={async (values) => {
              const hide = message.loading('正在保存');
              try {
                const res = await updateIntl({
                  ...values,
                  id: record?.id,
                })
                hide();
                if (res?.code === 0) {
                  message.success('保存成功，即将刷新');
                  actionRef.current?.reloadAndRest?.()
                  return true;
                } else {
                  message.error('保存失败，请重试');
                  return false;
                }
              } catch (error) {
                hide();
                message.error('保存失败，请重试');
                return false;
              }
            }}
            columns={columns as any}
          />,
          <Popconfirm
            key="del"
            title="删除国际化"
            description={<>
              <p>确认删除 <b>{record?.intlKey}</b> 国际化?</p>
            </>}
            onConfirm={async () => {
              const hide = message.loading('正在删除');

              try {
                const res = await batchDelIntl({
                  idList: [record?.id]
                })
                hide();
                if (res.code === 0) {
                  message.success('删除成功');
                  actionRef.current?.reloadAndRest?.()
                  return true
                } else {
                  hide();
                  message.error('删除失败请重试！');
                  return false;
                }
              } catch (e) {
                hide();
                message.error('删除失败请重试！');
                return false;
              }
            }}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>
          ,
        ];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="国际化"
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 'max-content'}}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key={'add'}
            trigger={<Button
              type="primary"
              key="primary"
              onClick={() => {
                addForm.resetFields()
                addForm.setFieldsValue({
                  intlKey: randomString(6),
                })
              }}
            >
              <PlusOutlined/> 新建
            </Button>}
            layoutType={'ModalForm'}
            form={addForm}
            modalProps={{
              width: 500,
              title: '新增国际化'
            }}
            // rowProps={{
            //   gutter: [16, 16],
            // }}
            // colProps={{
            //   span: 12,
            // }}
            // grid={false}
            onFinish={async (values) => {
              const hide = message.loading('正在保存');

              try {
                const res = await addIntl({
                  ...values,
                })
                hide();
                if (res?.code === 0) {
                  message.success('保存成功，即将刷新');
                  actionRef.current?.reloadAndRest?.()
                  return true;
                } else {
                  message.error('保存失败，请重试');
                  return false;
                }
              } catch (error) {
                hide();
                message.error('保存失败，请重试');
                return false;
              }
            }}
            columns={columns as any}
          />
          ,
        ]}
        request={async ({current, pageSize,...params}) => {
          // @ts-ignore
          const res = await getIntlPage({
            page: current,
            size: pageSize,
            ...params
          })

          return {
            data: res?.data?.current_data,
            total: res?.data?.total_records,
          }
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              Modal.confirm({
                title: `确认删除 ${selectedRowsState.length} 条数据?`,
                content: `请谨慎操作，删除后不可恢复`,
                async onOk() {
                  const hide = message.loading('正在删除');

                  try {
                    const res = await batchDelIntl({
                      idList: selectedRowsState?.map((item: any) => item.id)
                    })
                    hide();
                    if (res.code === 0) {
                      message.success('删除成功');
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.()
                      return true
                    } else {
                      hide();
                      message.error('删除失败请重试！');
                      return false;
                    }
                  } catch (e) {
                    hide();
                    message.error('删除失败请重试！');
                    return false;
                  }

                }
              })
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
    </PageContainer>
  );
};

export default TableList;
